import Taro from '@tarojs/taro'
let app = {
  apiUri: 'http://localhost/aiyanbaike/zhongsheng-server/public',  // 本地服务器
  imageUri: 'http://localhost/aiyanbaike/zhongsheng-server/public/', // 本地服务器
  //  apiUri: 'https://experts.bayou-tech.cn', // 百用服务器
  //  imageUri: 'https://experts.bayou-tech.cn/', // 百用服务器
  // apiUri: 'https://experts.huduo.tech', // 正式服务器
  // imageUri: 'https://experts.huduo.tech/', // 正式服务器
  // apiUri: 'https://texperts.huduo.tech', // 测试服务器
  // imageUri: 'https://texperts.huduo.tech/', // 测试服务器
  // apiUri: 'https://z.coral3.com/zhongsheng-server/public',
  // imageUri: 'https://z.coral3.com/zhongsheng-server/public/',
  // wsUri: 'ws://127.0.0.1:8889',
  wsUri: 'wss://byim.bayou-tech.cn',
  current: {name:'张三'}, 
  flow: {
    kps: [],
    current_item_index: 0,
    type: ''
  },
  eyesphoto:'',
  eyesvideo:'',
  eyesfile:'',
  inquiry_answer_id:'',
  dingdanid:'',
  dingdanname:'',
  chatArr:[],
  zixun:[],
  doctorid:'',
  sockets: [],
  ct_articles: [], // 即时聊天患教
  ct_flow: {}, // 即时聊天随访
  sessionKey: '',
  back_index:1, //设置标签页面的返回层级
  share_page: '', // 转发页面路径
  project_id:'',

  closeSockets() {
    var sockets = this.sockets;
    for (var i = 0; i < sockets.length; i++) {
      var socket = sockets[i];
      socket.close();
    }
    this.sockets = [];
  },
  getToken: function() {
    // return 'eyJpdiI6ImQ0d3h5Vll0N0FucjVkQWZEUE0zQmc9PSIsInZhbHVlIjoiSHpaUTV2VFlsNk1pOUZPWkhydzNSQTI0QXZkMHpQYVc4bVltN0xXVFVkVGtVQ3VwOGNOQ3pEbHVXMHQwR1lHUUZiRzV0dTl3dCtqUXRXdG02MkE2MUE9PSIsIm1hYyI6IjU1YTk1NjUwYTYwMjgwNzZkNGRmOWU0Y2IxMmY5MjA4OGVkODRkMWJjODUxMTU2OWZhYWI3MTdmMzRkMTI4Y2QifQ==';
    return Taro.getStorageSync('token');
  },
  get: function(url, data, callback) {
    data.token = this.getToken();
    Taro.request({
      url: this.apiUri + '/' + url,
      method: 'GET',
      data: data
    }).then(res => {
      callback(res);
    });
  },
  post: function(url, data, callback) {
    data.token = this.getToken();
    Taro.request({
      url: this.apiUri + '/' + url,
      method: 'POST',
      data: data,
      dataType: 'json',
      header: {
        'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'
      }
    }).then(res => {
      callback(res);
    });
  },
  navigateTo: function(url) {
    Taro.navigateTo({
      url: url
    })
  },
  redirectTo: function(url) {
    Taro.redirectTo({
      url: url
    })
  },
  wxLogin: function(promoter_id) {
    var me = this;
    console.log("获取微信code");
    // 登录
    Taro.login({
      success: res => {
        console.log("code="+res.code);
        me.post('doctor/wx_login', { code: res.code}, function(res) {
          console.log('微信信息');
          console.log(res); 

          var result = res.data.result;
          if (res.data.status != 200 || me.isEmpty(result.info.weixin_openid)) {
            console.log('程序出错啦');
            me.toastMessage('程序出错啦~');
            return;
          }

          Taro.setStorageSync('token', res.data.result.data);
          me.current = res.data.result.info;
          me.sessionKey = res.data.result.session_key;
          if (promoter_id) {  // 医生绑定助手
            me.bindPromoter(promoter_id);
          }

          if(me.isEmpty(result.info.gzh_openid)) { // 微信公众号openid不存在
            console.log('跳转到微信公众号授权页');
            me.redirectTo('/pages/doctorpages/blank/blank'); // 跳转到空白页获取微信公众号openid
          }else {  // 云学院信息存在
            me.decidePage(result.info);
          }
        })
      }
    }) 
  },
  bindPromoter: function(promoter_id) {
    app.post('web/doctor/bind_promoter', {promoter_id: promoter_id}, function(res) {

    });
  },
  toBlank: function() {
    if (!this.isEmpty(this.share_page)) {
      console.log('转发页面');
      var auth_status = this.current.auth_status;
      if (auth_status == '未认证' || auth_status == '申请中' || auth_status == '审核不通过') {
        this.redirectTo('/pages/doctorpages/firstEntry/firstEntry');
      } else {
        var page = this.share_page;
        this.share_page = '';
        this.redirectTo(page);
      }
    } else {
      //  this.redirectTo('/pages/doctorpages/blank/blank');  // 生产环境打开
      this.decidePage(this.current);  // 测试环境打开
    }
  },
  decidePage: function decidePage(userInfo) {
    let me = this;
    if (me.isEmpty(userInfo)) {
      userInfo = {};
    }
    var auth_status = userInfo.auth_status;
    if (me.isEmpty(auth_status)) {
      auth_status = '未认证';
    }

    console.log('决定去哪里',userInfo)

    if (me.isEmpty(userInfo.head_image) || me.isEmpty(userInfo.nickname) || me.isEmpty(userInfo.phone)) {
      //没登录的跳转去登录提示页面
      this.redirectTo('/pages/doctorpages/firstEntry/firstEntry');
    } else if (auth_status == '未认证') { //跳转去填写资料
      //this.redirectTo('/pages/center/pages/doctorcertified/doctorcertified');
      this.redirectTo('/pages/doctorpages/firstEntry/firstEntry');
    } else if (auth_status == '申请中' || auth_status == '审核不通过') {
      this.redirectTo('/pages/center/pages/doctorstatus/doctorstatus');
    } else {
      this.redirectTo('/pages/doctorpages/homepage/homepage');
    }
  },
  //弹出提示框,只有确认的警告框
  alertTab:function(contentText){
    Taro.showModal({
      title: '提示',
      content:contentText,
      showCancel: false
    });
  },
  //解析返回的字符串对象
  transObjStr:function(str){
    let arr=str.substr(1,str.length-2).split(',');
    let obj={};
    for(let val of arr){
      let sArr=val.split(':');
      obj[sArr[0]]=sArr[1];
    }
    return obj;
  },
  //用于弹出提示框来判断
  isConfirm:function(text,success,fail){
    Taro.showModal({
      title:'提示',
      content:text,
    }).then(res=>{
      console.log(res);
      if(res.confirm){
         if(success){
           success();
         }
      }else{
        if(fail){
          fail();
        }
      }
    })
  },
  //判断图片路径是否是http开头
  picturejudgment:function(src){
    if(src){
      if(src.substr(0,4)==='http'){
      return src;
    }else{
      return this.imageUri+src;
    }
    }
  },
  getPath: function(path) {
    if (!path) {
      return path;
    }
    if (path.indexOf('http://') != -1 || path.indexOf('https://') != -1) {
      return path;
    }
    return this.imageUri + path;
  },
  success: function(title, callback) {
    Taro.showToast({
      title: title,
      icon: 'success',
      duration: 1000
    }).then(callback)
  },
  toast: function(title, callback) {
    Taro.showToast({
      title: title,
      icon: 'none',
      duration: 2000
    }).then(callback)
  },
  toastMessage: function(title, callback) {
    Taro.showToast({
      title: title,
      icon: 'none',
      duration: 2000
    }).then(callback)
  },
  isEmpty: function(value) {
    if (value !== 0 && !value) {
      return true;
    }
    if ((value instanceof Array) && value.length <= 0) {
      return true;
    }
    return false;
  },
  checkPoneFormat: function(value) {
    return /^1\d{10}$/.test(value);
  },
  getQueryString(query, key) {
    let arr = query.split('=');
    return arr[1];
  },
  navigateBack: function(url) {
    Taro.navigateBack({
      url: url
    })
  },
  reLaunch: function(url) {
    Taro.reLaunch({
      url: url
    })
  },
  dateFormate(date, fmt) {
    var o = {
        "M+": date.getMonth() + 1, //月份 
        "d+": date.getDate(), //日 
        "h+": date.getHours(), //小时 
        "m+": date.getMinutes(), //分 
        "s+": date.getSeconds(), //秒 
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
        "S": date.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  },
  showShareMenu() {
    Taro.showShareMenu({});
  },
  hideStr(str) {
    if (!str) 
      return str;

    return str.substr(0, 1) + "**";  
  },
  // images格式： ["a.png", "b.png", ...]
  prviewImage(current_image, images) {
    for (var i = 0; i < images.length; i++) {
      images[i] = this.getPath(images[i]);
    }
    Taro.previewImage({
      urls: images,
      current: current_image
    })
  },
  inArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == value) {
        return true;
      }
    }
    return false;
  },
  obj_to_query(obj) {
    var query = '';
    for (var key in obj) {
      query += key + '=' + obj[key] + '&';
    }
    return query.slice(0, -1);
  }
  
};

export default app;